﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace bonus.Controllers
{
	/// <summary>
	/// 公告管理器
	/// </summary>
	public class NoticeController : Controller
	{

		/// <summary>
		/// 公告列表
		/// </summary>
		/// <returns></returns>
		public ActionResult Index()
		{
			Repository.Repository tool = new Repository.Repository();

			var list = tool.GetMany<Models.Notice>(new BsonDocument(), "AddDT:-1");

			return View(list);
		}

		/// <summary>
		/// 发布公告
		/// </summary>
		/// <returns></returns>
		public ActionResult Add()
		{
			return View();
		}

		/// <summary>
		/// 发布公告
		/// </summary>
		/// <param name="title">公告标题</param>
		/// <param name="content">公告内容</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Add(string title, string content)
		{
			Repository.Repository tool = new Repository.Repository();

			Models.Notice entity = new Models.Notice();
			entity._id = ObjectId.GenerateNewId();
			entity.AddDT = DateTime.Now;
			entity.Title = title;
			entity.Content = content;
			entity.IsCampay = false;
			entity.IsCenter = false;
			entity.IsUser = false;


			var result = tool.AddOneAsync(entity);

			return Json(new { Code = "OK", Msg = "发布成功" });
		}

		/// <summary>
		/// 删除公告
		/// </summary>
		/// <param name="id">公告标识</param>
		/// <returns></returns>
		public JsonResult Del(string id)
		{
			Repository.Repository tool = new Repository.Repository();
			var result = tool.DeleteOneAsync<Models.Notice>(id);
			return Json(new { Code = "OK", Msg = "删除成功" });
		}


		/// <summary>
		/// 修改公告显示权限
		/// </summary>
		/// <param name="id">公告标识</param>
		/// <param name="type">修改权限类型</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult StopUser(string id, int type)
		{
			Repository.Repository tool = new Repository.Repository();
			var entity = tool.GetOne<Models.Notice>(id);
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "公告不存在" });
			}

			if (type == 0)//用户
			{
				var updatau = Builders<Models.Notice>.Update.Set("IsUser", !entity.IsUser);

				var resultu = tool.UpdateOne(id, updatau);

				return Json(new { Code = "OK", Msg = (entity.IsUser ? "已显示" : "未显示") });
			}
			else if (type == 1)//服务中心
			{
				var updatau = Builders<Models.Notice>.Update.Set("IsCenter", !entity.IsCenter);

				var resultu = tool.UpdateOne(id, updatau);

				return Json(new { Code = "OK", Msg = (entity.IsCenter ? "已显示" : "未显示") });

			}
			else if (type == 2)//公司
			{
				var updatau = Builders<Models.Notice>.Update.Set("IsCampay", !entity.IsCampay);

				var resultu = tool.UpdateOne(id, updatau);

				return Json(new { Code = "OK", Msg = (entity.IsCampay ? "已显示" : "未显示") });
			}

			return Json(new { Code = "FAIL", Msg = "类型错误" });

		}

	}
}